//
// Created by hsj on 2022/1/14.
//
#include <iostream>
#include <cstring>
#include "t_class_memery.h"

namespace my_class_memery{
    //初始化静态成员变量
    int StringBad::num_strings = 0;

    StringBad::StringBad(const char *s){
        len = std::strlen(s);
        str = new char[len + 1];//last put '\0'
        std::strcpy(str,s);
        ++num_strings;
    }

    StringBad::StringBad(){
        /*len = 3;
        str = new char [len + 1];
        std::strcpy(str,"C++");
        ++num_strings;*/
        len = 0;
        str = new char [len + 1];
        str[0] = '\0';
        ++num_strings;
        /**
        //或者空指针表示
        str = NULL;
        str = nullptr;*/
    }

    StringBad::~StringBad(){
        --num_strings;
//        cout<<"num_strings len: "<<num_strings<<endl;
        delete [] str;
    }
    void StringBad::numStringsPrint(){
        cout<<"numStringsPrint:"<<this->num_strings<<endl;
    }

    //友元函数，不属于类
    std::ostream & operator<<(std::ostream &os,const StringBad &sb){
        cout<<sb.str<<endl;
        return os;
    }

    //定义一个显示的复制构造函数
    StringBad::StringBad(const StringBad &sb){
        ++num_strings;
        len = sb.len;
        str = new char[len + 1];
        std::strcpy(str,sb.str);
    }
    //定义一个显示的重载赋值运算符
    //不需要：++num_strings; 原因是默认构造函数已经有了
    StringBad & StringBad::operator=(const StringBad &sb){
        //校验同一个对象
        if (this == &sb){
            return *this;
        }
        //释放自己原始的内存
        delete [] str;
        len = sb.len;
        str = new char[len + 1];
        std::strcpy(str,sb.str);
        return *this;
    }
    StringBad & StringBad::operator=(const char *cp){
        //校验同一个对象(str)
        if (this->str == cp){
            return *this;
        }
        //释放自己原始的内存
        delete [] str;
        len = std::strlen(cp);
        str = new char[len + 1];
        std::strcpy(str,cp);
        return *this;
    }
}
